package cn.yuhe.user.service.impl;

import cn.yuhe.basic.constants.BaseConstants;
import cn.yuhe.basic.dto.SmsCodeDto;
import cn.yuhe.basic.exception.BusinessException;
import cn.yuhe.basic.utils.MD5Utils;
import cn.yuhe.basic.utils.StrUtils;
import cn.yuhe.org.domain.Employee;
import cn.yuhe.user.domain.Logininfo;
import cn.yuhe.user.domain.User;
import cn.yuhe.user.mapper.LogininfoMapper;
import cn.yuhe.user.mapper.UserMapper;
import cn.yuhe.user.service.ILogininfoService;
import cn.yuhe.user.service.IUserService;
import cn.yuhe.basic.service.impl.BaseServiceImpl;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yuhe
 * @since 2022-07-06
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ILogininfoService logininfoService;
    
    /** 
    * @Title: registerPhone
    * @Description: 根据手机号校验
    * @Author: Mr.Qiu
    * @Version: 1.0
    * @Date:  2022/7/6 19:15  
    * @Parameters: [smsCodeDto]
    * @Return void
    */
    @Override
    public void registerPhone(SmsCodeDto smsCodeDto) {
        // 获取邮箱
        String email = smsCodeDto.getEmail();
        // 获取电话参数
        String phone = smsCodeDto.getPhone();
        // 手机验证码的值
        String phoneCodeValue = smsCodeDto.getPhoneCodeValue();
        // 获取第二次密码的值
        String confirmPassword = smsCodeDto.getConfirmPassword();
        // 获取第一次密码的值
        String password = smsCodeDto.getPassword();
        // 1,为空校验
        if (StringUtils.isEmpty(phoneCodeValue) || StringUtils.isEmpty(confirmPassword) || StringUtils.isEmpty(password)) {
            throw new BusinessException("参数不能为空！");
        }
        if (StringUtils.isEmpty(phone) && StringUtils.isEmpty(email)) {
            throw new BusinessException("参数不能为空！");
        }
        String phoneCodeKey = "";
        // 拼接事务键
        if (StringUtils.isEmpty(phone)) {
            phoneCodeKey = BaseConstants.VerifyCodeConstant.BUSINESS_REGISTER_KEY + email;
            System.out.println("pk"+phoneCodeKey);
        } else {
            phoneCodeKey = BaseConstants.VerifyCodeConstant.BUSINESS_REGISTER_KEY + phone;
        }
        // 用拼接事务键取值 看有没有验证码
        System.out.println("后面的key="+phoneCodeKey);
        Object phoneCodeValueRedis  = redisTemplate.opsForValue().get(phoneCodeKey);
        // 2,两次手机号是否正确
        System.err.println(phoneCodeValueRedis);
        if (phoneCodeValueRedis == null) {
            throw new BusinessException("验证码已失效，请重新获取！");
        }
        // 3,判断验证码是否正确
        String phoneCode  = phoneCodeValueRedis.toString().split(":")[1];
        if (!phoneCode.equalsIgnoreCase(phoneCodeValue)){
            throw new BusinessException("手机验证码错误，请重新输入！");
        }
        // 4,两次密码是否一致
            if (!password.equals(confirmPassword)) {
            throw new BusinessException("两次密码不一致，请重新输入！");
        }
        // 5,判断用户是否注册
        User user;
        if (StringUtils.isEmpty(phone)){
            user = userMapper.loadByPhone2(email);
        } else {
            user = userMapper.loadByPhone(phone);
        }
        if (user != null){
            throw new BusinessException("用户已注册，请直接登录，如果忘记密码，请点击忘记密码！");
        }
        // 6.对user进行赋值操作
        user = smsCodeDto2User(smsCodeDto);
        userMapper.save(user);
        // 7,保存logininfo
        Logininfo logininfo = User2Logininfo(user);
        logininfoService.save(logininfo);
        // 8，将logininfo主键设置到user表
        user.setLogininfoId(logininfo.getId());
        userMapper.update(user);

    }



    /**
    * @Title: smsCodeDto2User
    * @Description: 将smsCodeDto的值赋值给user
    * @Author: Mr.Qiu
    * @Version: 1.0
    * @Date:  2022/7/6 20:59
    * @Parameters: [smsCodeDto]
    * @Return cn.yuhe.user.domain.User
    */
    private User smsCodeDto2User(SmsCodeDto smsCodeDto) {
        // 1.获取前台参数填写参数
        String phone = smsCodeDto.getPhone();
        // 1.1获取邮箱
        String email = smsCodeDto.getEmail();
        // 2.创建一个User对象
        User user = new User();
        // 3,设置user用户名，初始将电话设为名字
        if (StringUtils.isEmpty(phone)) {
            user.setUsername(email);
            user.setEmail(email);
        } else {
            user.setUsername(phone);
            user.setPhone(phone);
        }
        // 5,生成32位盐值
        String salt = StrUtils.getComplexRandomString(32);
        // 6.生成加盐密码
        String saltPassword  = MD5Utils.encrypByMd5(salt + smsCodeDto.getPassword());
        // 7,将加盐密码设置到user
        user.setPassword(saltPassword);
        // 8,将盐值设置到user
        user.setSalt(salt);
        return user;
    }

    /** 
    * @Title: User2Logininfo
    * @Description: 将user的值赋值给logininfo
    * @Author: Mr.Qiu
    * @Version: 1.0
    * @Date:  2022/7/6 21:20  
    * @Parameters: [user]
    * @Return cn.yuhe.user.domain.Logininfo
    */
    private Logininfo User2Logininfo(User user) {
        // 2.创建一个Logininfo对象
        Logininfo logininfo = new Logininfo();
        // 3.将user利用工具类复制到logininfo
        BeanUtils.copyProperties(user,logininfo);
        // 4,将权限设置为1
        logininfo.setType(1);
        return logininfo;
    }

    // =============================关联表互动=======================================

    @Override
    public void update(User user) {
        userMapper.update(user);
        Logininfo logininfo = user2Logininfo(user);
        logininfoService.update(logininfo);
    }

    @Override
    public void remove(Long id) {
        Long logininfoId = userMapper.loadById(id).getLogininfoId();
        logininfoService.remove(logininfoId);
        userMapper.remove(id);
    }


    // 2,初始化logininfo方法
    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(0);
        return logininfo;
    }

}
